import constant from '@/config/constant'
import {digit} from "ele-admin/packages/util";

/**
 * 保存或获取数据
 * @param data
 * @param key
 * @returns {string}
 */

function dataStorage(key = 'token', data = null) {
  if (data === false) {
    sessionStorage.removeItem(key)
  } else if (data !== null) {
    sessionStorage.setItem(key, data)
  } else {
    return sessionStorage.getItem(key)
  }
}

export {dataStorage}

/**
 * 保存或获取 Object 数据
 * @param key
 * @param data
 * @returns {any}
 */
export function dataObjectStorage(key, data = null) {
  if (data) {
    dataStorage(key, JSON.stringify(data))
  } else {
    try {
      let result = dataStorage(key)
      return result ? JSON.parse(result) : null;
    } catch (e) {
      return null
    }
  }
}

/**
 * 随机字符串
 * @param len
 * @returns {string}
 */
export function randomString(len = 16) {
  let t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
    a = t.length,
    n = "";
  for (let i = 0; i < len; i++) n += t.charAt(Math.floor(Math.random() * a));
  return n
}

/**
 * 常量状态格式化
 * @param status 值
 * @param type  常量类型
 * @param defaultVal  常量类型
 * @returns {string|*}
 */
export function constantFormatHtml(status = '', type = '', defaultVal = false) {
  if (status !== '' && type !== '') {
    return constant[type][status] ? constant[type][status] : defaultVal;
  }
  return '';
}

/**
 * 表格列定义批量设置默认值
 * @param columns
 * @param force
 * @returns {*}
 */
export function setColumnsDefaultKey(columns, force = false) {
  if (columns instanceof Array) {
    return setColumnsDefaultSetKey(columns, force)
  } else if (columns instanceof Object) {
    Object.keys(columns).forEach(key => {
      columns[key] = setColumnsDefaultSetKey(columns[key], force)
    })
    return columns
  }
}

function setColumnsDefaultSetKey(columns, force = false) {
  let key = 1
  columns.map(res => {
    res.columnKey = force || !res.columnKey ? key.toString() : res.columnKey
    key += 1
    return res
  })
  return columns
}

/**
 * 根据环境区分域名
 * @param path
 * @returns {string}
 */
export function envDistinguishDomain(path = '') {
  // let domain = ['development', 'develop'].includes(process.env.NODE_ENV) ?
  let domain = process.env.NODE_ENV === 'development' ?
    process.env.VUE_APP_API_BASE_URL :
    document.location.origin + process.env.VUE_APP_API_BASE_URL
  return domain + path;
}

/**
 * 秒转成 时:分
 * @param time
 * @returns {string}
 */
export function timeHourFormat(time) {
  let hour = Math.floor(time / 3600);
  let minute = Math.floor(time % 3600 / 60);
  hour = (hour < 10) ? '0' + hour : hour;
  minute = (minute < 10) ? '0' + minute : minute;
  return hour + ':' + minute;
}

/**
 * 获取下拉框数据
 * @param type 常量类型
 * @param isAll 是否包含全部  用于全部得值
 * @param filter 过滤得值
 * @param valuePrefix 值前缀
 * @returns {[{label: string, value: string}]|[]}
 */
export function downConstantList(type = '', isAll = '', filter = [], valuePrefix = false) {
  let result = isAll !== false ? [{label: '全部', value: isAll}] : [];
  if (constant[type]) {
    let value = constant[type];
    for (let key in value) {
      if (filter.length === 0 || !filter.includes(Number(key))) {
        let val = valuePrefix ? valuePrefix + key : Number(key)
        result.push({label: value[key], value: val});
      }
    }
  }
  return result;
}

/**
 * 表格头增加tip提示信息
 * renderHeader: (h, {column}) => {
      return headerTipRender(h, column, "1. 这是一个测试提示<br/> 2. 测试");
   }
 * @param h
 * @param column
 * @param tooltipContent
 * @returns {*}
 */
export function headerTipRender(h, column, tooltipContent) {
  let html = '';
  if (Array.isArray(tooltipContent)) {
    tooltipContent.forEach(val => {
      html += '<p class="pd2">' + val + '</p>';
    })
  } else {
    html = tooltipContent;
  }

  return h('span', [
    h('span', column.label),
    h(
      'el-tooltip',
      {
        props: {
          effect: 'dark',
          placement: 'top',
        },
      },
      [
        h('i', {
          class: 'el-icon-question',
          style: 'margin-left:3px;',
        }),
        h('div', {
          slot: 'content',
          domProps: {
            innerHTML: html
          }
        })
      ]
    )
  ]);
}

export function formatSecond(second) {
  second = Number(second)
  let hr = parseInt(second / 60 / 60 % 24)
  let min = parseInt(second / 60 % 60)
  let sec = parseInt(second % 60)
  return `${digit(hr, 2)}:${digit(min, 2)}:${digit(sec, 2)}`;
}


/**
 * 数字保量小数位
 * @param number
 * @param digit
 * @param defaultVal
 * @returns {string}
 */
export function decimalPlaces(number, digit = 2, defaultVal = '') {
  return digit !== false && (number || Number(number) === 0) ? parseFloat(number).toFixed(digit) : defaultVal
}

/**
 * 获取变量类型
 * @param obj
 * @returns {string}
 */
export function variableTypeOf(obj) {
  let res = Object.prototype.toString.call(obj).split(' ')[1]
  res = res.substring(0, res.length - 1).toLowerCase()
  return res
}
